using UnityEngine;
using System;
using System.Collections;


public class SASprite : MonoBehaviour
{
	
	[HideInInspector] public SAMapPos mapPos = new SAMapPos();
	
	[HideInInspector] public SATexture saTexture = null;
	


	public SASprite ()
	{

	}

	static GameObject spriteObject = null;
	private static GameObject Create()
	{
		if ( spriteObject == null ) 
		{
			spriteObject = (GameObject)Resources.Load( "Prefabs/SASprite" );
			DontDestroyOnLoad( spriteObject );
		}

		return (GameObject)Instantiate( spriteObject );
	}

	public static void DestorySprite( GameObject obj , bool b = false )
	{
		SASprite spr = obj.GetComponent< SASprite >();
		
		if ( spr.saTexture != null )
		{
			if ( b )
			{
				spr.saTexture.releaseData();
			}

			spr.saTexture = null;
		}

		Destroy( obj );
	}

	public static GameObject CreateTerrainSprite()
	{
		GameObject obj = Create();
		obj.transform.parent = SAMapManager.instance.terrainLayer.transform;
		obj.transform.localScale = new Vector3( 1.0f , 1.0f , 1.0f );

		return obj;
	}

	// building..or npc ?
	public static GameObject CreateCreatureSprite()
	{
		GameObject obj = Create();
		obj.transform.parent = SAMapManager.instance.creatureLayer.transform;
		obj.transform.localScale = new Vector3( 1.0f , 1.0f , 1.0f );

		return obj;
	}

	public static GameObject CreateBattleTerrainSprite()
	{
		GameObject obj = Create();
		obj.transform.parent = SABattleMapManager.instance.terrainLayer.transform;
		obj.transform.localScale = new Vector3( 1.0f , 1.0f , 1.0f );
		
		return obj;
	}
	
	public static GameObject CreateBattleCreatureSprite()
	{
		GameObject obj = Create();
		obj.transform.parent = SABattleCreautreManager.instance.creatureLayer.transform;
		obj.transform.localScale = new Vector3( 1.0f , 1.0f , 1.0f );
		
		return obj;
	}
		
	IEnumerator loadData( SATexture texture )
	{
		texture.loadData();
		
		yield return 0;
	}


	public void setTerrainID( int id )
	{
		saTexture = SATextureConfig.instance.getTerrainTexture( id );
		saTexture.initData();

		if ( !saTexture.hasData ) 
		{
			// error
			//if ( GameSetting.UseAsync ) 
			//{
			//	// has bug,
			//	StartCoroutine( loadData( saTexture ) );
			//	saTexture.hasData = true;
			//}
			//else
			//{
				saTexture.loadData();
			//}
		}

		
		SpriteRenderer renderer = (SpriteRenderer)gameObject.renderer;
		renderer.sprite = saTexture.sprite;
	}




	public void setPos( int x , int y , bool z = false )
	{
		mapPos.mapGrid.setValue( x , y );

		//float posX = mapPos.mapGrid.realPosX - SAMapGrid.GridXHalfHalf * saTexture.e + SAMapGrid.GridXHalfHalf * saTexture.s;
		float posY = mapPos.mapGrid.realPosY - SAMapGrid.GridYHalf + SAMapGrid.GridYHalfHalf * saTexture.e + SAMapGrid.GridYHalfHalf * saTexture.s;

		transform.localPosition = new Vector3( mapPos.mapGrid.realPosX , mapPos.mapGrid.realPosY , z ? GameDefine.getZ( posY ) : 0 );
	}

}

